<template>
  <div>
    <!-- 卡片视图 -->
    <the-table
      :data="state.tableData"
      :columns="state.columns"
      :layout="['addBtn', 'search', 'column', 'importBtn', 'exportBtn']"
      :pageInfo="state.pageInfo"
      @clearInput="getData"
      :total="state.total"
      @handleExport="exportExcel"
      @handleImport="state.excelInDialogVisible = true"
      @handleAdd="state.addDialogVisuble = true"
      @search="querySearch"
      @pageInfoChange="pageInfoChange"
    >
      <template v-slot:extractbtn>
        <div class="block" style="display: flex;">
          <span style="line-height:32px">所属地查询：</span>
          <regional-league @areaChange="areaSearch" />
        </div>
      </template>

      <el-table-column
        prop="name"
        label="企业名称"
        width="180"
        align="left"
        v-if="state.columns[0].show"
      />
      <el-table-column
        prop="cityInfo"
        label="所属地"
        width="180"
        align="center"
        v-if="state.columns[1].show"
      >
        <template #default="scope">
          <span v-if="scope.row.cityInfo">{{ scope.row.cityInfo.merName }}</span>
          <el-tag v-else type="success">暂无信息</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" v-if="state.columns[2].show" />
      <el-table-column prop="uscc" label="统一社会信用代码" width="180" v-if="state.columns[3].show">
        <template #default="scope">
          <span v-if="scope.row.uscc">{{ scope.row.uscc }}</span>
          <el-tag v-else type="warning">暂无信息</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="modiTime" label="编辑时间" />操作
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <el-button type="text" size="small" @click="openEditDialog(scope.row)">
            <el-icon class="el-input__icon">
              <edit />
            </el-icon>编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            style="color: #f56c6c"
            @click="deleteById(scope.row.id)"
          >
            <el-icon class="el-input__icon">
              <delete />
            </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>
    <!-- 添加企业对话框 -->
    <el-dialog title="添加企业信息" v-model="state.addDialogVisuble" width="50%" @open="clearAddForm">
      <el-form
        label-position="right"
        ref="formRef"
        label-width="140px"
        :model="state.addCompanyForm"
        :rules="state.rules"
      >
        <el-form-item label="企业名称:" prop="name">
          <el-input v-model="state.addCompanyForm.name" placeholder="请输入企业名"></el-input>
        </el-form-item>
        <el-form-item label="所属地:">
          <regional-league @areaChange="areaChange"></regional-league>
        </el-form-item>
        <el-form-item label="地址:" prop="address">
          <el-input v-model="state.addCompanyForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码:" prop="uscc">
          <el-input v-model="state.addCompanyForm.uscc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.addDialogVisuble = false">取 消</el-button>
          <el-button type="primary" @click="addConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改企业信息 -->
    <!--  -->
    <el-dialog
      title="修改企业信息"
      v-model="state.editDialogVisible"
      width="50%"
      @close="state.isShowArea = false"
    >
      <el-form
        label-position="right"
        label-width="140px"
        :model="state.editForm"
        ref="formRef"
        :rules="state.rules"
      >
        <el-form-item label="企业名称:" prop="name">
          <el-input v-model="state.editForm.name" placeholder="请输入企业名"></el-input>
        </el-form-item>
        <el-form-item label="所属地:" prop="merName">
          <regional-league
            v-if="state.isShowArea"
            @areaChange="editArea"
            :provinceName="provinceName"
            :cityName="cityName"
          ></regional-league>
        </el-form-item>
        <el-form-item label="地址:" prop="address">
          <el-input v-model="state.editForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码:" prop="uscc">
          <el-input v-model="state.editForm.uscc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer #default="scope">
        <span class="dialog-footer">
          <el-button @click="state.editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editConfirm()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入excel -->
    <el-dialog title="导入文件" v-model="state.excelInDialogVisible" width="27%" @closed="clearUpload">
      <el-upload
        class="upload-demo"
        drag
        ref="uploadRef"
        :headers="headers"
        :auto-upload="true"
        action="http://112.74.61.241:8081/orgs/ents/authExcelFile/"
        :before-upload="beforeUpload"
        :multiple="false"
        :on-exceed="handleExceed"
        accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        :limit="1"
        :http-request="uploadExcel"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          拖拽文件或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">一次只能上传一个文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="state.excelInDialogVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="state.excelInDialogVisible = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { getBusiness, addBusiness, searchBusiness, updateBusiness, deleteBusiness, exportOrainationExcel, uploadBusExcel, searchBusinessByArea } from '@/api/OrganizationManagement/business'
import { getAllProvince } from '@/api/Area/area';
import RegionalLeague from '@/components/OrganizationManagement/RegionalLeague.vue'
import TheTable from "@/components/common/TheTable.vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineComponent, reactive, ref, Ref, nextTick, onMounted } from "vue";
import { addLogs } from '#/Home/Home'
export interface tableObj {
  id: string,
  name: string,
  sname: null,
  city: number,
  address: string,
  uscc: string,
  provinceName: null,
  cityName: null,
  createTime: string,
  modiTime: string,
  introduction: null,
  cityInfo: {
    id: number,
    name: string,
    sname: string,
    level: number,
    cityCode: string,
    yzCode: string,
    merName: string,
    longitude: number,
    latitude: number,
    pinyin: string,
    pid: number
  }
}
export interface pro {
  value: string,
  label: string,
  id: string,
}
export default defineComponent({
  components: {
    RegionalLeague,
    TheTable
  },
  setup() {
    const state = reactive({
      tableData: [] as tableObj[],    //数组内元素对象类型
      pageInfo: {
        isShow: true,
        pageSize: 5,
        pageNum: 1,
        placeholder: "请输入内容",
      },
      total: 0,
      temppageInfo: {
        isShow: true,
        pageSize: 5,
        pageNum: 1,
        placeholder: "请输入企业信息"
      },
      queryInfo: '',      //关键字模糊查询
      queryAreaInfo: '',   //地区模糊查询
      formMerName: '',
      addCompanyForm: {
        name: '',
        city: '',
        address: '',
        uscc: ''
      },
      editForm: {
        name: '',
        city: '',
        address: '',
        uscc: ''
      },
      editId: '',    //要修改的目标ID
      provinceOps: [] as pro[],
      cityOpts: [],
      addDialogVisuble: false,
      excelInDialogVisible: false,
      excelOutDialogVisible: false,
      editDialogVisible: false,
      rules: {
        name: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入企业地址", trigger: "blur" },
        ],
        city: [
          { required: true, message: "请输入企业邮编", trigger: "blur" },
        ],
        merName: [
          { required: true, message: "请选择企业所属地", trigger: "blur" },
        ],
        uscc: [
          { required: true, message: "请输入统一社会信用代码", trigger: "blur" },
        ],
      },
      isShowArea: true,
      columns: [
        { name: "企业名称", show: true },
        { name: "所属地", show: true },
        { name: "地址", show: true },
        { name: "统一社会信用码", show: true },
      ],
    })

    const formRef: any = ref(null);    //表单Dom对象ref
    let uploadRef: any = ref(null)
    const fileExcelList: Ref<Array<any>> = ref([])
    const headers = {
      'Content-Type': 'multipart/form-data'
    }
    let provinceName: Ref<string> = ref('')
    let cityName: Ref<string> = ref('')

    //获取表单信息
    const getData = async (): Promise<void> => {
      const res: any = await getBusiness(state.pageInfo.pageNum, state.pageInfo.pageSize)
      if (res.data.ret === 0) {
        state.tableData = res.data.orgs.ents.content
        state.total = res.data.orgs.ents.totalElements
      }
      // console.log(res)
    }
    getData()

    const getProvinceInfo = async (): Promise<void> => {
      const res: any = await getAllProvince()
      if (res.data.ret === 0) {
        state.provinceOps = res.data.provs.map((e: any) => {
          let obj = {
            id: e.id,
            value: e.name,
            label: e.name
          }
          return obj
        })
      }
    }

    getProvinceInfo()

    const pageInfoChange = (type: string, newValue: number): void => {
      type === 'size' ? state.pageInfo.pageSize = newValue : state.pageInfo.pageNum = newValue;
      getData()
    }

    const deleteById = async (id: string): Promise<void> => {
      const confirmRes = await ElMessageBox.confirm(
        "此操作将永久删除该企业信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err: any) => err);
      if (confirmRes === 'confirm') {
        const res: any = await deleteBusiness(id)
        if (res.data.ret === 0) {
          addLogs({
            userId: window.sessionStorage.getItem("userId"),
            behavior: "删除企业信息成功"
          })
          ElMessage.success('删除成功')
          getData()
        }
      }
    }
    //添加企业表单提交
    const addConfirm = (): void => {
      if (!formRef) return
      formRef.value.validate((valid: any) => {
        if (valid) {
          addEvent()
        } else {
          ElMessage.info('请输入完整表单信息')
        }
      })
    }

    const addEvent = async (): Promise<void> => {
      await addBusiness(state.addCompanyForm).then((res: any) => {
        if (res.data.ret === 0) {
          ElMessage.success(res.data.msg)
          getData()
          state.addDialogVisuble = false
        }
      }).catch((e) => {
        console.log('请求出错', e)
      })
    }

    //添加表单对象打开清空
    const clearAddForm = (): void => {
      nextTick(() => {
        formRef.value.resetFields()
      })
    }

    const openEditDialog = (obj: any): void => {
      state.editForm.name = obj.name
      state.editForm.address = obj.address
      state.editForm.uscc = obj.uscc
      state.editId = obj.id
      state.isShowArea = true
      // state.editDialogVisible = true
      if (obj.cityInfo) {
        // nextTick(() => {
        provinceName.value = obj.cityInfo.merName.split(",")[1]
        cityName.value = obj.cityInfo.merName.split(",")[2]
        // })
      }
      state.editDialogVisible = true
    }
    //修改地址
    const editArea = (areaInfo: any, cityInfo: any): void => {
      state.editForm.city = cityInfo.id
    }

    const editConfirm = (): void => {
      editEvent()
    }

    //修改企业表单提交
    const editEvent = async (): Promise<void> => {
      const res: any = await updateBusiness(state.editId, state.editForm)
      if (res.data.ret === 0) {
        ElMessage.success(res.data.msg)
        getData()
        state.editDialogVisible = false
      }
    }

    //模糊查询
    const querySearch = async (queryInfo: string): Promise<void> => {
      state.pageInfo.pageNum = 1
      const res: any = await searchBusiness(queryInfo, state.pageInfo.pageNum, state.pageInfo.pageSize)
      state.tableData = res.data.orgs.ents.content
      state.total = res.data.orgs.ents.totalElements
    }

    const areaChange = (areaInfo: any, cityInfo: any): void => {
      console.log(cityInfo)
      state.editForm.city = cityInfo.id
      state.addCompanyForm.city = cityInfo.id
    }

    const areaSearch = async (areaInfo: any, cityInfo: any): Promise<void> => {
      console.log(cityInfo)
      await searchBusinessByArea(cityInfo.id, state.pageInfo.pageNum, state.pageInfo.pageSize).then((res: any) => {
        if (res.data.ret === 0) {
          state.tableData = res.data.orgs.ents.content
          state.total = res.data.orgs.ents.totalElements
          ElMessage.success('查询成功')
          console.log(res)
        }
      })
    }

    const exportExcel = async (): Promise<void> => {
      await exportOrainationExcel().then(res => {
        if (res.status === 200) {
          let data: any = res.data
          const blob = new Blob([data], {  // res 为后台返回数据
            type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
          });
          ElMessage.success('导出成功')
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = `企业信息.xlsx`;
            elink.style.display = 'none';
            elink.target = '_blank';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
        }
      })
    }

    const beforeUpload = (file: any) => {
      const isText = file.type === 'application/vnd.ms-excel';
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isText && !isTextComputer) {
        ElMessage.warning('请上传excel格式文件！');
        return
      }
      const fileSize = file.size / 1024 / 1024 < 5
      if (!fileSize) {
        ElMessage.warning('文件大小不能超过5M');
        return
      }
      return (isText || isTextComputer);
    }

    //文件数量超过limit时触发的方法
    const handleExceed = (files, fileList) => {
      console.log(files, fileList)
      ElMessage.warning('当前限制选择 1 个文件，请删除后继续上传');
    }

    const uploadExcel = async (item): Promise<void> => {
      console.log(item)
      const fileObj = item.file;
      // console.log(fileObj)
      const form = new FormData();
      form.append('file', fileObj);
      // console.log(form)
      await uploadBusExcel(form).then((res: any) => {
        if (res.data.ret === 0) {
          ElMessage.success('文件：' + fileObj.name + res.data.msg);
          fileExcelList.value = [];
          getData()
        }
      }).catch(() => {
        ElMessage.error('文件：' + fileObj.name + '上传失败！');
      }).finally(() => {
        fileExcelList.value = [];
      });
    }
    const clearUpload = () => {
      uploadRef.value.clearFiles()
    }

    return {
      state,
      pageInfoChange,
      openEditDialog,
      deleteById,
      addConfirm,
      editConfirm,
      querySearch,
      areaChange,
      editArea,
      exportExcel,
      uploadRef,
      areaSearch,
      formRef,
      clearAddForm,
      getData,
      beforeUpload,
      uploadExcel,
      handleExceed,
      provinceName,
      cityName,
      headers,
      clearUpload
    }
  }
})
</script>

<style scoped>
.el-select {
  width: 120px;
}
.el-input {
  width: 80%;
  padding-right: 50px;
}
/* .input-with-select .el-input-group__prepend {
  background-color: #fff;
} */
.el-pagination {
  padding-top: 60px;
  display: flex;
  justify-content: center;
}

.el-input__suffix {
  right: 55px;
}
</style>
